import {Component, OnInit} from '@angular/core';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import * as _ from 'underscore';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss']
})
export class AddComponent implements OnInit {
  form: FormGroup;
  id: any;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private router: Router,
    private location: Location,
    private route: ActivatedRoute,
  ) {
    this.form = this.fb.group({
      id: [],
      description: ['', [Validators.required]],
      fromHost: ['localhost', [Validators.required]],
      fromPort: ['3306', [Validators.required]],
      fromUsername: ['root', [Validators.required]],
      fromPassword: ['root', [Validators.required]],
      toHost: ['localhost', [Validators.required]],
      toPort: ['3307', [Validators.required]],
      toUsername: ['root', [Validators.required]],
      toPassword: ['root', [Validators.required]],
      tables: this.fb.array([]),
    });
  }

  addField(e?: MouseEvent) {
    if (e) {
      e.preventDefault();
    }
    const table = this.form.get('tables') as FormArray;
    const item = this.tableItem();
    table.push(item);
  }

  removeField(i) {
    const tables = this.form.get('tables') as FormArray;
    tables.removeAt(i);
  }

  tableItem(): FormGroup {
    return this.fb.group({
      id: [],
      name: ['', [Validators.required]]
    });
  }

  ngOnInit() {
    this.route.paramMap.subscribe(res => {
      this.id = res.get('id');
      if (this.id) {
        this.loadData();
      } else {
        this.addField();
      }
    });
  }

  submitForm(value: any): void {
    for (const key in this.form.controls) {
      if (key) {
        this.form.controls[key].markAsDirty();
        this.form.controls[key].updateValueAndValidity();
      }
    }
    this.http.post('/api/environment', value).subscribe(() => {
      this.router.navigate(['/environment']);
    });
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.form.reset();
    for (const key in this.form.controls) {
      if (key) {
        this.form.controls[key].markAsPristine();
        this.form.controls[key].updateValueAndValidity();
      }
    }
    const table = this.form.get('tables') as FormArray;
    const item = this.tableItem();
    table.clear();
    table.push(item);
  }

  backward() {
    this.location.back();
  }

  loadData() {
    this.http.get('/api/environment/' + this.id).subscribe(res => {
      this.form.patchValue(res);
      const tables = this.form.get('tables') as FormArray;
      _.map(res[`tables`], o => {
        const item = this.tableItem();
        item.patchValue(o);
        tables.push(item);
      });
    });
  }
}
